package com.shaodongbo.httpclient;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int GET_PHONE = 1001;
    private Handler handler;
    private Button btn_get;
    private Button btn_post;
    private EditText edt_phone;
    private TextView txt_result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_get = findViewById(R.id.btn_get);
        btn_post = findViewById(R.id.btn_post);
        edt_phone = findViewById(R.id.edt_phone);
        txt_result = findViewById(R.id.txt_result);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == GET_PHONE){
                    String result = (String) msg.obj;
                    txt_result.setText(result);
                    return true;
                }
                return false;
            }
        });

        btn_get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = edt_phone.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpGet(phone);
                    }
                }).start();
            }
        });

        btn_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = edt_phone.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpPost(phone);
                    }
                }).start();
            }
        });
//         useHttpClientGetThread();
//        useHttpUrlConnectionGetThread();
    }

    private void useHttpPost(String phone) {
        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        HttpPost httpPost = new HttpPost(url);
        HttpClient httpClient = new DefaultHttpClient();
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        nameValuePairList.add(new BasicNameValuePair("mobileCode", phone));
        nameValuePairList.add(new BasicNameValuePair("userID", ""));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            String htmlContent = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            Log.e(TAG, htmlContent);

            Message message = Message.obtain();
            message.what = GET_PHONE;
            message.obj = htmlContent;
            handler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=string&userID=string
    private void useHttpGet(String phone) {
        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=";
        url = url.concat(phone).concat("&userID=");
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int code = httpResponse.getStatusLine().getStatusCode();
            Log.e(TAG, "code = " + code);
            String htmlContent = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            Log.e(TAG, htmlContent);

            Message message = Message.obtain();
            message.what = GET_PHONE;
            message.obj = htmlContent;
            handler.sendMessage(message);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * HttpClient GET请求网络
     * */
    private void useHttpClientGetThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                useHttpClientGet("http://www.baidu.com");
            }
        }).start();
    }

    /**
     * HttpUrlConnection POST请求网络
     * */
    private void useHttpUrlConnectionGetThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                useHttpUrlConnectionPost("http://www.baidu.com");
            }
        }).start();
    }

    /**
     * 设置默认请求参数，并返回HttpClient
     *
     * @return HttpClient
     * */
    private HttpClient createHttpClient(){
        HttpParams mDefaultHttpParams = new BasicHttpParams();
        // 设置链接超时
        HttpConnectionParams.setConnectionTimeout(mDefaultHttpParams, 15000);
        // 设置请求超时
        HttpConnectionParams.setSoTimeout(mDefaultHttpParams, 15000);
        HttpConnectionParams.setTcpNoDelay(mDefaultHttpParams, true);
        HttpProtocolParams.setVersion(mDefaultHttpParams, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(mDefaultHttpParams, HTTP.UTF_8);
        // 持续握手
        HttpProtocolParams.setUseExpectContinue(mDefaultHttpParams, true);
        HttpClient mHttpClient = new DefaultHttpClient(mDefaultHttpParams);
        return mHttpClient;
    }

    /**
     * 使用HttpClient的GET请求网络
     *
     * @param  url
     * */
    private void useHttpClientGet(String url){
        HttpGet mHttpGet = new HttpGet(url);
        mHttpGet.addHeader("Connection", "keep-Alive");

        try {
            HttpClient mHttpClient = createHttpClient();
            HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            int code = mHttpResponse.getStatusLine().getStatusCode();
            if (null != mHttpEntity){
                InputStream mInputStream = mHttpEntity.getContent();
                String response = converStreamToString(mInputStream); // converStreamToString方法将请求结果转换成String类型
                Log.i("Dongbo", "请求状态码" + code + "\n请求结果：\n" + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void useHttpClientPost(String url){
        HttpPost mHttpPost = new HttpPost(url);
        mHttpPost.addHeader("Connection", "Keep-Alive");
        try {
            HttpClient mHttpClient = createHttpClient();
            List<NameValuePair> postParams = new ArrayList<>();
            // 要传递的参数
            postParams.add(new BasicNameValuePair("username", "moon"));
            postParams.add(new BasicNameValuePair("password", "123"));
            mHttpPost.setEntity(new UrlEncodedFormEntity(postParams));
            HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            int code = mHttpResponse.getStatusLine().getStatusCode();
            if (null != mHttpEntity){
                InputStream mInputStream = mHttpEntity.getContent();
                String response = converStreamToString(mInputStream); // converStreamToString方法将请求结果转换成String类型
                Log.i("Dongbo", "请求状态码" + code + "\n请求结果：\n" + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将请求结果转换为String类型
     *
     * @return String
     * @throws IOException
     * */
    private String converStreamToString(InputStream mInputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(mInputStream));
        StringBuffer stringBuffer = new StringBuffer();
        String line = null;
        while ((line = reader.readLine()) != null){
            stringBuffer.append(line + "\n");
        }
        String response = stringBuffer.toString();
        return response;
    }

    // HttpURLConnection
    private void useHttpUrlConnectionPost(String url){
        InputStream mInputStream = null;
        HttpURLConnection mHttpURLConnection = UrlConnManager.getHttpURLConnection(url);
        try {
            List<NameValuePair> postParams = new ArrayList<>();
            postParams.add(new BasicNameValuePair("username", "moon"));
            postParams.add(new BasicNameValuePair("password", "123"));
            UrlConnManager.postParams(mHttpURLConnection.getOutputStream(), postParams);
            mHttpURLConnection.connect();
            mInputStream = mHttpURLConnection.getInputStream();
            int code = mHttpURLConnection.getResponseCode();
            String response = converStreamToString(mInputStream);
            Log.i("Dongbo", "请求状态码:" + code + "\n请求结果:\n" + response);
            mInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
